package com.xingchen.feima.star.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xingchen.feima.common.utils.R;
import com.xingchen.feima.star.entity.Rectangle;
import com.xingchen.feima.star.entity.SingleTransportationPlanVersion;
import com.xingchen.feima.star.entity.fvo.SingleTransportationPlan;
import com.xingchen.feima.star.entity.fvo.SingleTransportationPlanCondition;
import com.xingchen.feima.star.service.RectangleService;
import com.xingchen.feima.star.service.SingleTransportationPlanVersionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 长方形表，每个长方形用来代表某机组的某个时间段，时间段用来安装乏燃料或者是不可装料时间窗
 * </p>
 *
 * @author yangxc
 * @since 2025-02-22
 */
@Api(tags = "长方形管理")
@Transactional
@RestController
@RequestMapping("/star/rectangle")
public class RectangleController {
    @Autowired
    private RectangleService rectangleService;
    @Autowired
    private SingleTransportationPlanVersionService singleTransportationPlanVersionService;


    // 根据方案版本id获取长方形列表
    @ApiOperation(value = "根据方案版本id获取长方形列表")
    @GetMapping("/getSingleTransportationPlanByVersionId/{versionId}")
    public R getSingleTransportationPlanByVersionId(
            @ApiParam(name = "versionId", value = "方案版本id", required = true)
            @PathVariable Long versionId){

        List<Rectangle> rectangleList = rectangleService.list(new QueryWrapper<Rectangle>().eq("version_id", versionId));
        SingleTransportationPlanVersion singleTransportationPlanVersion = singleTransportationPlanVersionService.getOne(new QueryWrapper<SingleTransportationPlanVersion>().eq("id", versionId));

        Map<String, Object> map = new HashMap<>();
        map.put("rectangleList", rectangleList);
        map.put("singleTransportationPlanVersion", singleTransportationPlanVersion);

        return R.ok().data("items", map);
    }


    @ApiOperation(value = "保存单次运输计划")
    @PostMapping("/saveSingleTransportationPlan")
    public R saveSingleTransportationPlan(
            @ApiParam(name = "singleTransportationPlan", value = "单次运输计划", required = true)
            @RequestBody SingleTransportationPlan singleTransportationPlan) {
        // 保存方案版本后，获取方案版本的id，然后赋值给方案，保存方案
        SingleTransportationPlanVersion singleTransportationPlanVersion = singleTransportationPlan.getSingleTransportationPlanVersion();
        singleTransportationPlanVersionService.save(singleTransportationPlanVersion);
        List<Rectangle> rectangleList = singleTransportationPlan.getRectangleList();
        rectangleList.forEach(rectangle -> {
            rectangle.setVersionId(singleTransportationPlanVersion.getId());
        });
        rectangleService.saveBatch(rectangleList);

        return R.ok().message("保存方案成功");
    }

    @ApiOperation(value = "调用python后端获取单次运输计划")
    @PostMapping("/getSingleTransportationPlan")
    public R getSingleTransportationPlan(
            @ApiParam(name = "singleTransportationPlanCondition", value = "单次运输计划条件", required = true)
            @RequestBody SingleTransportationPlanCondition singleTransportationPlanCondition) {

        String singleTransportationPlanUrl = "http://localhost:5000/getSingleTransportationPlan";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(singleTransportationPlanUrl);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonInputString = objectMapper.writeValueAsString(singleTransportationPlanCondition);
            StringEntity entity = new StringEntity(jsonInputString, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity());
                // System.out.println("Response from Python server: " + responseBody);

                // 解析响应数据
                Map<String, Object> responseMap = objectMapper.readValue(responseBody, new TypeReference<Map<String, Object>>() {});
                List<Rectangle> rectangleList = objectMapper.convertValue(responseMap.get("rectangle_list"), new TypeReference<List<Rectangle>>() {});
                Map<String, Object> singleTransportationPlanVersion = objectMapper.convertValue(
                        responseMap.get("single_transportation_plan_version"), new TypeReference<Map<String, Object>>() {});

                Map<String, Object> map = new HashMap<>();
                map.put("rectangleList", rectangleList);
                map.put("singleTransportationPlanVersion", singleTransportationPlanVersion);

                return R.ok().data("items", map);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
    }
}
